import React from 'react';
import { createRoot } from 'react-dom/client';
import Toast from "./Toast";


class ToastManager {
    private toastContainer: HTMLDivElement | null = null;
    constructor() {
        this.initContainer()
    }
    
    private initContainer() {
        if (!this.toastContainer) {
            this.toastContainer = document.createElement('div');
            this.toastContainer.id = 'toast-container';
            this.toastContainer.style.position = 'fixed';
            this.toastContainer.style.bottom = '1rem';
            this.toastContainer.style.right = '1rem';
            this.toastContainer.style.zIndex = '1060';
            document.body.appendChild(this.toastContainer);
        }
    }

    show(message: string, type: 'success' | 'danger' | 'info' | 'warning' = 'info', autoCloseTime: number = 5000) {
        const toastId = `toast-${Date.now()}`;
        const toastElement = document.createElement('div');
        toastElement.id = toastId;
        if (this.toastContainer) {
            this.toastContainer.appendChild(toastElement);
        }
        const root = createRoot(toastElement);
        root.render(React.createElement(Toast, {
            type,
            message,
            onClose: () => this.onClose(root, toastId),
            autoClose: true,
            autoCloseTime
        }));

        return {
            hide: () => {
                this.onClose(root, toastId);
            }
        };
    }

    public success(message: string, autoCloseTime: number = 5000) {
        return this.show(message, 'success', autoCloseTime);
    }

    public error(message: string, autoCloseTime: number = 5000) {
        console.error('ERROR: ', message);
        return this.show(message, 'danger', autoCloseTime);
    }

    public info(message: string, autoCloseTime: number = 5000) {
        console.info('INFO: ', message);
        return this.show(message, 'info', autoCloseTime);
    }

    public warning(message: string, autoCloseTime: number = 5000) {
        console.warn('WARNING: ', message);
        return this.show(message, 'warning', autoCloseTime);
    }

    public clear() {
        if (this.toastContainer) {
            this.toastContainer.innerHTML = '';
        }
    }
    
    private onClose(root: any, toastId: string) {
        const element = document.getElementById(toastId);
        if (element) {
            root.unmount();
            element.remove();
        }
    }
}

export default ToastManager; 